package org.wanda.pv.service.user.impl;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.wanda.pv.model.user.SysPermission;
import org.wanda.pv.model.user.SysRole;
import org.wanda.pv.model.user.SysUser;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    Dao dao;


    @Override
    public UserDetails loadUserByUsername(String loginname) throws UsernameNotFoundException {
        SysUser user = dao.fetch(SysUser.class, Cnd.where("loginname", "=", loginname));

        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        if (user!=null){

           // List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

            // 获取用户角色
            user = dao.fetchLinks(user, null);
            List<SysRole> sysRoles = user.getSysRoles();

            //List<String> roleNames = sysRoles.stream().map(item -> item.getAliasName()).collect(Collectors.toList());
            sysRoles.forEach(role->{
                simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role.getAliasName()));
                System.out.println(role.getAliasName());
                dao.fetchLinks(role,null);
                List<SysPermission> sysPermissions = role.getSysPermissions();
                sysPermissions.forEach(permission->{
                    simpleGrantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermission()));
                });

            });



        }

        return new User(user.getLoginname(),user.getPassword(),simpleGrantedAuthorities);
    }
}
